#!/usr/bin/env bash
#
# Copyright (C) 2000-2025 Kern Sibbald
# License: BSD 2-Clause; see file LICENSE-FOSS
#
# Run a simple backup of the Bacula build directory
#   then restore it.
#
TestName="backup-bacula-test"
JobName=backup
. scripts/functions

scripts/cleanup
scripts/copy-confs

#
# Zap out any schedule in default conf file so that
#  it doesn't start during our test
#
outf="$tmp/sed_tmp"
echo "s%  Schedule =%# Schedule =%g" >${outf}
cp $scripts/bacula-dir.conf $tmp/1
sed -f ${outf} $tmp/1 >$scripts/bacula-dir.conf

change_jobname BackupClient1 $JobName
start_test

cat <<END_OF_DATA >$tmp/bconcmds
@output /dev/null
messages
@$out $tmp/log1.out
setdebug level=4 storage=File1
label volume=TestVolume001 storage=File1 pool=File slot=1 drive=0
show job=$JobName
show jobs
run job=$JobName yes
wait
messages
@# 
@# now do a restore
@#
@$out $tmp/log2.out  
setdebug level=4 storage=File1
restore where=$tmp/bacula-restores select all done
yes
wait
messages
quit
END_OF_DATA

run_bacula
check_for_zombie_jobs storage=File1
stop_bacula

cat <<END_OF_DATA >$tmp/bconcmds
@$out /dev/null
messages
@$out $tmp/log1.out
setdebug level=4 storage=File1
run job=$JobName yes
wait
messages
@# 
@# now do a restore
@#
@$out $tmp/log2.out  
#setbandwidth client=$CLIENT limit="100 kb/s"
setdebug level=4 storage=File1
restore where=$tmp/bacula-restores select all done
yes
wait
messages
@output $tmp/log31.out
.jlist jobs reviewed=1
@output $tmp/log32.out
update jobid=1 reviewed=1
@output $tmp/log33.out
.jlist jobs reviewed=1
quit
END_OF_DATA

#
# Now do a second backup after making a few changes
#
touch ${cwd}/build/src/dird/*.o
echo "test test" > ${cwd}/build/src/dird/xxx
dd if=/dev/zero of=${cwd}/build/src/dird/yyy bs=65537 count=1

run_bacula
check_for_zombie_jobs storage=File1
stop_bacula

grep '{' $tmp/log31.out | perl -MJSON -e '$l = <>; $obj = JSON::decode_json($l); exit (scalar(@{ $obj->{data} }) == 0);'
if [ $? != 1 ]; then
    print_debug "ERROR: Should find 0 job reviewed in $tmp/log/31.out"
    estat=1
fi

grep '{' $tmp/log33.out | perl -MJSON -e '$l = <>; $obj = JSON::decode_json($l); exit (scalar(@{ $obj->{data} }) == 1);'
if [ $? != 1 ]; then
    print_debug "ERROR: Should find 1 job reviewed in $tmp/log33.out"
    estat=1
fi

check_two_logs
check_restore_diff

rm -f ${cwd}/build/src/dird/xxx ${cwd}/build/src/dird/yyy

end_test
